from django.shortcuts import render, redirect
from app02 import models
from app02.utils.form import UserModelForm


def user_list(request):
    """ 用户管理 """
    queryset = models.UserInfo.objects.all()
    # for obj in queryset:
    #
    #     # print(obj.id, obj.name, obj.create_time.strftime("%Y-%m-%d"), obj.get_gender_display(), obj.depart.title)
    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    if request.method == 'GET':
        """ 添加用户 """
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, "user_add.html", context)

    # 获取用户输入数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')

    models.UserInfo.objects.create(name=user, password=pwd, age=age, account=account, create_time=ctime, gender=gender, depart_id=depart_id)
    return redirect("/user/list/")


def user_model_form_add(request):
    """ 添加用户modelform """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, "user_model_form_add.html", {"form": form})

    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request, "user_model_form_add.html", {"form": form})


def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':

        form = UserModelForm(instance=row_object)
        return render(request, "user_edit.html", {"form": form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request, "user_edit.html", {"form": form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")